package com.tebiecloud.store.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.base.client.constants.BaseConstants;
import com.tebiecloud.base.client.model.entity.BaseAccount;
import com.tebiecloud.common.constants.CommonConstants;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.PageResult;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.*;
import com.tebiecloud.store.client.constatns.StoreConstants;
import com.tebiecloud.store.client.model.entity.Store;
import com.tebiecloud.store.client.model.entity.StoreRole;
import com.tebiecloud.store.client.model.entity.StoreStaff;
import com.tebiecloud.store.client.model.vo.StoreStaffVo;
import com.tebiecloud.store.server.service.StoreRoleService;
import com.tebiecloud.store.server.service.StoreService;
import com.tebiecloud.store.server.service.StoreStaffService;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.store.server.service.feign.BaseUserServiceClient;
import com.tebiecloud.store.server.service.feign.MpminiAccountRefServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 员工表 前端控制器
 * @author tebie
 * @date 2019-09-15
 */
@RestController
@RequestMapping("/storestaff")
public class StoreStaffController {

    @Autowired
    private StoreStaffService storeStaffService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private StoreRoleService storeRoleService;

    @Autowired
    private BaseUserServiceClient baseUserServiceClient;

    @Autowired
    private MpminiAccountRefServiceClient mpminiAccountRefServiceClient;

    /**
     * 员工的个人信息
     * @return
     */
    @PostMapping("info")
    public ResultBody<StoreStaffVo> get(
            @RequestParam(value = "storeStaffId") Long storeStaffId) {
        QueryWrapper<StoreStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_staff_id", storeStaffId);
        StoreStaff storeStaff = storeStaffService.getOne(queryWrapper, false);
        if(storeStaff == null) {
            return ResultBodyUtils.failed("信息不存在");
        }
        StoreStaffVo storeStaffVo = getStoreStaffVo(storeStaff);
        return ResultBodyUtils.ok(storeStaffVo);
    }

    /**
     * 获取门店列表或者店员列表
     * @param page
     * @param limit
     * @param storeId
     * @return
     */
    @PostMapping(value = "list")
    public ResultBody list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "storeId", required = false) Long storeId
    ) {
        // 用户查看门店列表
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if(BaseConstants.ACCOUNT_DOMAIN_USER.equalsIgnoreCase(securityUserDetails.getDomain())) {

            // 过滤条件
            QueryWrapper<StoreStaff> queryWrapper = new QueryWrapper();
            if(storeId!=null){//店员列表
                queryWrapper.eq("store_id",storeId);
                //只读取员工和店员
                List<String> roles = new ArrayList<>();
                roles.add("SHOPOWNER");
                roles.add("CLERK");
                queryWrapper.in("role_code",roles);
                queryWrapper.orderByDesc("entry_time");
            }else{//所在门店列表
                queryWrapper.eq("user_id", securityUserDetails.getUserId());
                queryWrapper.orderByDesc("switch_time");
            }
            // 查询数据
            IPage<StoreStaff> retStoreStaff = storeStaffService.page(new Page<StoreStaff>(page,limit),queryWrapper);
            IPage<StoreStaffVo> storeStaffVoIPage = new Page<>();
            storeStaffVoIPage.setTotal(retStoreStaff.getTotal());
            storeStaffVoIPage.setSize(retStoreStaff.getSize());
            storeStaffVoIPage.setPages(retStoreStaff.getPages());
            storeStaffVoIPage.setCurrent(retStoreStaff.getCurrent());
            storeStaffVoIPage.setSize(retStoreStaff.getSize());
            List<StoreStaffVo> storeStaffVoList = new ArrayList<>();
            if(retStoreStaff.getRecords()!=null && retStoreStaff.getRecords().size()>0){
                List<StoreStaff> storeStaffList = retStoreStaff.getRecords();
                for(StoreStaff storeStaff:storeStaffList ){
                    StoreStaffVo storeStaffVo = getStoreStaffVo(storeStaff);
                    storeStaffVoList.add(storeStaffVo);
                }
            }
            storeStaffVoIPage.setRecords(storeStaffVoList);
            return ResultBodyUtils.ok(storeStaffVoIPage);
        }
        QueryWrapper<StoreStaff> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("ct");
        return ResultBodyUtils.ok(storeStaffService.page(new PageParams(page,limit), queryWrapper));
    }

    /**
     * 切换门店
     * @return
     */
    @PostMapping("updateSwitchTime")
    public ResultBody updateSwitchTime(@RequestParam("storeId") long storeId) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();

        // 更新条件
        UpdateWrapper<StoreStaff> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", securityUserDetails.getUserId());
        updateWrapper.eq("store_id", storeId);

        // 更新内容
        StoreStaff storeStaffUpdate = new StoreStaff();
        storeStaffUpdate.setSwitchTime(new Date());

        // 更新操作
        storeStaffService.update(storeStaffUpdate, updateWrapper);

        return ResultBodyUtils.ok();
    }

    /**
     * 从StoreStaff信息获取StoreStaffVo
     * @param storeStaff
     * @return
     */
    private StoreStaffVo getStoreStaffVo(StoreStaff storeStaff) {
        StoreStaffVo storeStaffVo = new StoreStaffVo();
        storeStaffVo.setStoreId(storeStaff.getStoreId());
        storeStaffVo.setStoreStaffId(storeStaff.getStoreStaffId());
        storeStaffVo.setHeadimgurl(storeStaff.getHeadimgurl());
        storeStaffVo.setName(storeStaff.getName());
        storeStaffVo.setSex(storeStaff.getSex().intValue());
        storeStaffVo.setPhone(storeStaff.getPhone());
        storeStaffVo.setRoleCode(storeStaff.getRoleCode());
        storeStaffVo.setEntryTime(storeStaff.getEntryTime());
        storeStaffVo.setSwitchTime(storeStaff.getSwitchTime());

        // 门店信息
        if(storeStaff.getStoreId() != null) {
            Store store = storeService.getById(storeStaff.getStoreId());
            if (store != null) {
                storeStaffVo.setStoreName(store.getName());
            }
        }

        // 角色信息
        if(!StringUtils.isEmpty(storeStaff.getRoleCode())) {
            QueryWrapper<StoreRole> queryWrapperStoreRole = new QueryWrapper<>();
            queryWrapperStoreRole.eq("role_code", storeStaff.getRoleCode());
            StoreRole storeRole = storeRoleService.getOne(queryWrapperStoreRole, false);
            if(storeRole != null) {
                storeStaffVo.setRoleName(storeRole.getRoleName());
            }
        }

        return storeStaffVo;
    }


    /**
     * 添加员工接口
     * @param storeId
     * @param roleCode
     * @param phone
     * @return
     */
    @PostMapping("add")
    public ResultBody add(
            @RequestParam(value = "storeId") Long storeId,
            @RequestParam(value = "roleCode") String roleCode,
            @RequestParam(value = "staffName") String staffName,
            @RequestParam(value = "phone") String phone
    ) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long currentUserId = securityUserDetails.getUserId();
        //查询当前员工
        QueryWrapper<StoreStaff> storeStaffQueryWrapper = new QueryWrapper<>();
        storeStaffQueryWrapper.eq("user_id",currentUserId);
        storeStaffQueryWrapper.eq("store_id",storeId);
        StoreStaff storeStaff = storeStaffService.getOne(storeStaffQueryWrapper);
        if(storeStaff==null)return ResultBodyUtils.failed("查询当前员工失败");
        //限制当前员工权限
        if(StoreConstants.STORE_STAFF_CLERK.equals(storeStaff.getRoleCode())
                ||StoreConstants.STORE_STAFF_AGM.equals(storeStaff.getRoleCode())){
            return ResultBodyUtils.failed("权限不足，不能添加员工");
        }
        Long userId = null;
        //获取用户信息
        ResultBody<BaseAccount>  retGetBaseAccount = baseUserServiceClient.getBaseAccount(phone,null,null);
        if(retGetBaseAccount.getCode() == ResultEnum.OK.getCode()) {
            BaseAccount baseAccount = retGetBaseAccount.getData();
            if(baseAccount!=null){
                userId = baseAccount.getUserId();
                baseUserServiceClient.updateBaseAccount(baseAccount.getAccount(),1);
            }
        }else{
            // 添加用户信息
            ResultBody<BaseAccount> retAddBaseAccount = baseUserServiceClient.addBaseAccount(phone, RandomValueUtils.random(16),
                    BaseConstants.ACCOUNT_TYPE_STAFF_PHONE, BaseConstants.ACCOUNT_DOMAIN_USER, "员工",
                    staffName, "https://mggwx.oss-cn-shenzhen.aliyuncs.com/gumiho/shop/image/20190516/260220859b9f485e8cbd6b193f62cc78.png"
            );
            if(retAddBaseAccount.getCode() == ResultEnum.OK.getCode()) {
                BaseAccount baseAccount = retAddBaseAccount.getData();
                if(baseAccount!=null)userId = baseAccount.getUserId();
            }
        }
        if(userId!=null){
            //查询手机号是否存在
            QueryWrapper<StoreStaff> storeStaffQueryWrapper1 = new QueryWrapper<>();
            storeStaffQueryWrapper1.eq("store_id",storeId);
            storeStaffQueryWrapper1.eq("phone",phone);
            StoreStaff storeStaff1 = storeStaffService.getOne(storeStaffQueryWrapper1);
            if(storeStaff1==null){
                storeStaff1 = new StoreStaff();
                storeStaff1.setUserId(userId);
                storeStaff1.setStoreId(storeId);
                storeStaff1.setPhone(phone);
                storeStaff1.setRoleCode(roleCode);
                storeStaff1.setEntryTime(new Date());
                storeStaff1.setHeadimgurl("https://mggwx.oss-cn-shenzhen.aliyuncs.com/gumiho/shop/image/20190516/d9f49fe3ffa04a6896382a16ab648208.png");
                storeStaff1.setName(staffName);
                storeStaff1.setSex(2);
                storeStaffService.save(storeStaff1);
            }else{
                return ResultBodyUtils.failed("该员工已经在本门店");
            }
        }else{
            return ResultBodyUtils.failed("添加用户失败");
        }
        return ResultBodyUtils.ok();
    }

    /**
     * 删除员工
     * @param storeStaffId
     * @return
     */
    @PostMapping("remove")
    public ResultBody remove(
            @RequestParam(value = "storeStaffId") long storeStaffId
    ) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();

        //查询要删除员工
        QueryWrapper<StoreStaff> storeStaffQueryWrapper1 = new QueryWrapper<>();
        storeStaffQueryWrapper1.eq("store_staff_id",storeStaffId);
        StoreStaff storeStaff1 = storeStaffService.getOne(storeStaffQueryWrapper1);
        if(storeStaff1==null)return ResultBodyUtils.failed("查询要删除的员工失败");

        //查询当前员工
        QueryWrapper<StoreStaff> storeStaffQueryWrapper = new QueryWrapper<>();
        storeStaffQueryWrapper.eq("user_id",userId);
        storeStaffQueryWrapper.eq("store_id",storeStaff1.getStoreId());
        StoreStaff storeStaff = storeStaffService.getOne(storeStaffQueryWrapper);
        if(storeStaff==null)return ResultBodyUtils.failed("查询当前登录员工失败");

        //限制当前员工权限
        if(StoreConstants.STORE_STAFF_CLERK.equals(storeStaff.getRoleCode())
                ||StoreConstants.STORE_STAFF_AGM.equals(storeStaff.getRoleCode())){
            return ResultBodyUtils.failed("权限不足，不能删除员工");
        }
        //限制其他店长互删
        if(StoreConstants.STORE_STAFF_SHOPOWNER.equals(storeStaff.getRoleCode())
                && StoreConstants.STORE_STAFF_SHOPOWNER.equals(storeStaff1.getRoleCode())){
            return ResultBodyUtils.failed("店长不能删除店长");
        }
        //限制傻瓜用户
        if(storeStaff.getStoreStaffId()==storeStaffId){
            return ResultBodyUtils.failed("自己不能删除自己");
        }

        //是否最后一个
        if(storeStaff1!=null){
            QueryWrapper<StoreStaff> storeStaffQueryWrapper2 = new QueryWrapper<>();
            storeStaffQueryWrapper2.eq("phone",storeStaff1.getPhone());
            int count = storeStaffService.count(storeStaffQueryWrapper2);
            storeStaffService.remove(storeStaffQueryWrapper1);
            if(count==1){//关闭账号
                baseUserServiceClient.updateBaseAccount(storeStaff1.getPhone(),0);
            }
        }

        // 删除登录关联账户
        mpminiAccountRefServiceClient.removeMpminiAccountRef(-1, storeStaff1.getPhone());

        return ResultBodyUtils.ok();
    }

}
